<template>
  <v-container>
    <div id="settings-wrapper">
      <v-card
        id="settings"
        class="py-2 px-4"
        :color="hintColor"
        dark
        flat
        link
        min-width="40"
        style="position: fixed; top: 15px; right: 0px; border-radius: 8px; z-index: 1;"
      >
        <v-tooltip bottom>
          <template v-slot:activator="{ on, attrs }">
            <v-btn
              icon
              :color="hintColor"
              v-bind="attrs"
              v-on="on"
            >
              <v-icon v-if="systemStatus.healthy===STATUS_HEALTHY_INVALID">
                mdi-cog
                mdi-light
                mdi-inactive
              </v-icon>
              <v-icon v-if="systemStatus.healthy!==STATUS_HEALTHY_INVALID">
                mdi-cog
                mdi-light
                mdi-spin
              </v-icon>
            </v-btn>
            <strong>
              {{ healthyText }}
            </strong>
          </template>
          <span>{{ lanChar.uiSettings.UISettingsButtonHint }}</span>
        </v-tooltip>
      </v-card>

      <v-menu
        v-model="menu"
        :close-on-content-click="false"
        activator="#settings"
        bottom
        content-class="v-settings"
        right
        nudge-bottom="60"
        offset-x
        origin="top right"
        transition="scale-transition"
      >
        <v-card
          class="text-center mb-0"
          width="300"
        >
          <v-card-text>
            <strong class="mb-3 d-inline-block">{{ lanChar.uiSettings.UISettingsButtonTitle }}</strong>
            <v-divider class="my-1 secondary" />

            <v-row
              align="center"
              no-gutters
            >
              <v-col cols="auto">
                {{ lanChar.uiSettings.UISettingsDarkModeDescp }}
              </v-col>

              <v-spacer />

              <v-col cols="auto">
                <v-switch
                  v-model="$vuetify.theme.dark"
                  class="ma-0 pa-0"
                  color="secondary"
                  hide-details
                  :label="$vuetify.theme.dark.toString()"
                  @click="setDarkMode()"
                />
              </v-col>
            </v-row>

            <v-divider class="my-4 secondary" />

            <v-row
              align="center"
              no-gutters
            >
              <v-col cols="auto">
                {{ lanChar.uiSettings.UISettingsCHSModeDescp }}
              </v-col>

              <v-spacer />

              <v-col cols="auto">
                <v-switch
                  v-model="chineseMode"
                  class="ma-0 pa-0"
                  color="secondary"
                  hide-details
                  :label="`${chineseMode.toString()}`"
                  @click="setLanguage()"
                />
              </v-col>
            </v-row>

            <v-divider class="my-4 secondary" />
            <!-- <div class="my-12" /> -->
            <div>
              <strong class="mb-3 d-inline-block">{{ lanChar.uiSettings.UISettingsVendor }}</strong>
            </div>
          </v-card-text>
        </v-card>
      </v-menu>
    </div>
    <material-snackbar-tip
      v-model="snackbarDescp.snackbar"
      :type="snackbarDescp.snackbarType"
      :timeout="snackbarDescp.snackbarTimeout"
      v-bind="{
        bottom: true,
        right: true
      }"
      :text="snackbarDescp.snackbarContent"
    />
  </v-container>
</template>

<script>
  import globalDef from '@/util/globals'
  import lan from '@/util/lan-char'
  import * as mcAxios from '@/util/mcaxios'
  // Mixins
  import Proxyable from 'vuetify/lib/mixins/proxyable'

  // Vuex
  import { get, sync } from 'vuex-pathify'

  export default {
    name: 'UISettings',

    mixins: [Proxyable],

    data: () => ({
      lanChar: lan.GetLan(),
      STATUS_HEALTHY_INVALID: globalDef.STATUS_HEALTHY_INVALID,
      // snackbar data
      snackbarDescp: {
        snackbar: false,
        snackbarContent: 'snackbar content',
        snackbarTimeout: 2000,
        snackbarType: 'info',
      },
      color: '#E91E63',
      colors: [
        '#9C27b0',
        '#00CAE3',
        '#4CAF50',
        '#ff9800',
        '#E91E63',
        '#FF5252',
      ],
      menu: false,
      saveImage: '',

      statusTimer: 0,
      systemStatus: {
        start_date: '',
        is_init_complete: false,
        healthy: globalDef.STATUS_HEALTHY_INVALID,
      },
      chineseMode: false,
    }),

    computed: {
      ...sync('app', [
        'drawer',
        'drawerImage',
        'mini',
      ]),
      ...sync('user', [
        'drawer@gradient',
        'drawer@image',
      ]),
      ...get('user', [
        'images',
        'gradients',
      ]),
      healthyText: function () {
        return lan.FormatHealthy(this.systemStatus.healthy)
      },
      hintColor: function () {
        switch (this.systemStatus.healthy) {
          case 0:
            /* Working fine */
            return '#004D4080'
          case 1:
            /* Init not completed successfully */
            return '#DD2C0080'
          case 2:
            /* Configuration may be out of sync */
            return '#82771780'
          case 3:
            /* Connect VPP fail */
            return '#000000'
          case 4:
            /* Connect VPP OK */
            return '#004D4080'
          default:
            return '#000000'
        }
      },
    },

    watch: {
      color (val) {
        this.$vuetify.theme.themes[this.isDark ? 'dark' : 'light'].primary = val
      },
    },

    beforeDestroy () {
      clearInterval(this.statusTimer)
    },

    created () {
      this.getSystemInfo()
      this.startReflash()
      // this.getSystemStatus()
    },
    mounted () {
    },
    methods: {
      tipInfo (level, content, timeout) {
        this.snackbarDescp.snackbarType = level
        this.snackbarDescp.snackbarContent = content
        this.snackbarDescp.snackbarTimeout = timeout
        this.snackbarDescp.snackbar = true
      },
      reflashStatus () {
        // this.getSystemStatus()
      },
      startReflash () {
        clearInterval(this.statusTimer)
        this.statusTimer = setInterval(this.reflashStatus, globalDef.STATUS_QUERY_INTERVAL)
      },
      getSystemInfo () {
        const data = {
          request_type: 'system info get',
          instance_id: 'instance_id',
          sequence_no: 1000,
        }
        mcAxios.axiosGetConfig(data)
          .then((res) => {
            if (res.data.status === true) {
              this.chineseMode = (res.data.data.ui_language === 1)
              this.$vuetify.theme.dark = res.data.data.ui_darkmode
              this.lanChar = lan.SetLan(res.data.data.ui_language)
              globalDef.VueObject.$emit('lanChange', this.lanChar)
            } else {
              console.log('getSystemInfo resonse fail')
            }
          })
          .catch((e) => {
            console.log('getSystemInfo request fail: ' + e)
          })
      },
      getSystemStatus () {
        const data = {
          request_type: 'system status get',
          instance_id: 'instance_id',
          sequence_no: 1000,
        }
        mcAxios.axiosGetConfig(data)
          .then((res) => {
            if (res.data.status === true) {
              this.systemStatus = res.data.data
            } else {
              this.systemStatus.healthy = globalDef.STATUS_HEALTHY_INVALID
            }
            globalDef.RUNNING_STATUS = this.systemStatus
          })
          .catch((e) => {
            this.systemStatus.healthy = globalDef.STATUS_HEALTHY_INVALID
            globalDef.RUNNING_STATUS = this.systemStatus
          })
      },
      setLanguage () {
        this.lanChar = lan.SetLan(this.chineseMode ? 1 : 0)
        globalDef.VueObject.$emit('lanChange', this.lanChar)
        const data = {
          request_type: 'ui language set',
          instance_id: 'instance_id',
          sequence_no: 1000,
          data: {
            ui_language: (this.chineseMode ? 1 : 0),
          },
        }
        mcAxios.axiosSetConfig(data)
          .then((res) => {
            if (res.data.status === true) {
              this.tipInfo('success', this.lanChar.tipInfoOperateSuccess, globalDef.TIPINFO_DISPLAY_DURATION)
            } else {
              this.tipInfo('info', this.lanChar.tipInfoOperateRespFail + res.data.msg, globalDef.TIPINFO_DISPLAY_DURATION)
            }
          })
          .catch((e) => {
            this.tipInfo('error', this.lanChar.tipInfoOperateRequestFail + e, globalDef.TIPINFO_DISPLAY_DURATION)
          })
      },
      setDarkMode () {
        const data = {
          request_type: 'ui darkmode set',
          instance_id: 'instance_id',
          sequence_no: 1000,
          data: {
            ui_darkmode: this.$vuetify.theme.dark,
          },
        }
        mcAxios.axiosSetConfig(data)
          .then((res) => {
            if (res.data.status === true) {
              this.tipInfo('success', this.lanChar.tipInfoOperateSuccess, globalDef.TIPINFO_DISPLAY_DURATION)
            } else {
              this.tipInfo('info', this.lanChar.tipInfoOperateRespFail + res.data.msg, globalDef.TIPINFO_DISPLAY_DURATION)
            }
          })
          .catch((e) => {
            this.tipInfo('error', this.lanChar.tipInfoOperateRequestFail + e, globalDef.TIPINFO_DISPLAY_DURATION)
          })
      },
    },
  }
</script>

<style lang="sass">
  .v-settings
    .v-item-group > *
      cursor: pointer

    &__item
      border-width: 3px
      border-style: solid
      border-color: transparent !important

      &--active
        border-color: #00cae3 !important
</style>
